package com.zzp.sms.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author 佐斯特勒
 * <p>
 *  自定义成功认证处理类
 * </p>
 * @version v1.0.0
 * @date 2020/1/13 0:28
 * @see  CustomizeAuthenticationSuccessHandler
 **/
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest req,
                                        HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
        resp.setContentType("application/json;charset=utf-8");
        var map = new HashMap<String, Object>(6);
        map.put("code", 1);
        map.put("msg", "登录成功");

        var writer = resp.getWriter();

        writer.write(objectMapper.writeValueAsString(map));
        writer.flush();
        writer.close();
    }
}
